<?php
class MenuOptionValidatorSchema extends sfValidatorSchema
{
    protected function configure($options = array(), $messages = array())
    {
        $this->addMessage('Opción', 'Indique el nombre de la opción.');
        $this->addMessage('URL', 'Indique el URL al que redirige la opción.');
        $this->addMessage('empty', 'Debe crear al menos una opción');
    }

    protected function doClean($values)
    {
        $errorSchema = new sfValidatorErrorSchema($this);

        foreach($values as $key => $value)
        {
            $errorSchemaLocal = new sfValidatorErrorSchema($this);

            if($value['is_local'])
            {
                if(!$value['section_id'])
                {
                    $errorSchemaLocal->addError(new sfValidatorError($this, 'Opción'), 'Opción');
                }
            } else {
                // link is filled but no title
                if ($value['link'] && (!$value['title']))
                {
                    $errorSchemaLocal->addError(new sfValidatorError($this, 'Opción'), 'Opción');
                }

                // title is filled but no link
                if ($value['title'] && !$value['link'])
                {
                    $errorSchemaLocal->addError(new sfValidatorError($this, 'URL'), 'URL');
                }

                // some error for this embedded-form
                if (count($errorSchemaLocal))
                {
                    $errorSchema->addError($errorSchemaLocal, (string) $key);
                }
            }
            // no section, no title and no link, remove the empty values
            if (!$value['section_id'] && !$value['link'] && !$value['title'])
            {
                unset($values[$key]);
            }
        }

        if(!count($values))
        {
            $errorSchema->addError(new sfValidatorError($this, 'empty'), 'empty');
        }

        // throws the error for the main form
        if (count($errorSchema))
        {
            throw new sfValidatorErrorSchema($this, $errorSchema);
        }
        return $values;
    }
}

